<template>
  <div class="tree-filter-container">
    <el-input
      v-model="filterText"
      :placeholder="placeholder"
      clearable
      prefix-icon="Search"
      class="filter-input"
    />
    
    <el-tree
      ref="treeRef"
      :data="data"
      :props="defaultProps"
      :filter-node-method="filterNode"
      node-key="id"
      highlight-current
      class="filter-tree"
      @node-click="handleTreeNodeClick" 
    >
      <template #default="{ node, data }">
        <span class="custom-node">
          <el-icon class="node-icon">
            <component :is="data.icon || Folder" />
          </el-icon>
          <span class="node-label" :title="node.label">
            {{ node.label }}
          </span>
          <el-tag v-if="data.count" size="small" class="node-count">
            {{ data.count }}
          </el-tag>
        </span>
      </template>
    </el-tree>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElTree, ElInput, ElIcon, ElTag } from 'element-plus'
import { Search, Folder } from '@element-plus/icons-vue'
import type { TreeNode } from '@/types'


const props = withDefaults(defineProps<{
  data: TreeNode[]
  placeholder?: string
  filterFields?: string[]
}>(), {
  placeholder: '输入关键字搜索...',
  filterFields: () => ['label']
})

const emit = defineEmits<{
  nodeClick: [data: TreeNode, node: any]
}>()

const treeRef = ref<InstanceType<typeof ElTree>>()
const filterText = ref('')

const defaultProps = {
  children: 'children',
  label: 'label'
}

const filterNode = (value: string, data: TreeNode): boolean => {
  if (!value) return true
  const matchText = props.filterFields.some(field => {
    const fieldValue = data[field as keyof TreeNode]
    return fieldValue && String(fieldValue).toLowerCase().includes(value.toLowerCase())
  })
  if (matchText) return true
  if (data.children && data.children.length) {
    return data.children.some(child => filterNode(value, child))
  }
  return false
}

watch(filterText, (val) => {
  treeRef.value?.filter(val)
})

// ✅ 点击事件处理器
const handleTreeNodeClick = (data: TreeNode, node: any) => {
  
  emit('nodeClick', data, node)
}

defineExpose({
  getCheckedNodes: () => treeRef.value?.getCheckedNodes(),
  getCheckedKeys: () => treeRef.value?.getCheckedKeys(),
  setCheckedNodes: (nodes: TreeNode[]) => treeRef.value?.setCheckedNodes(nodes),
  setCheckedKeys: (keys: (string | number)[]) => treeRef.value?.setCheckedKeys(keys),
  expandAll: () => {
    const expandNodes = (nodes: TreeNode[]) => {
      nodes.forEach(node => {
        treeRef.value?.store.getNode(node.id)?.expand?.()
        if (node.children) expandNodes(node.children)
      })
    }
    expandNodes(props.data)
  },
  collapseAll: () => {
    treeRef.value?.store.root.childNodes.forEach(node => node.collapse?.())
  }
})
</script>